package com.bojin.studio.ubattery;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

public class MainService extends Service { 
	
    private NotificationManager mNotificationManager;
	private PendingIntent mPendingIntent;
	private Notification mNotification;
	 
	 private BroadcastReceiver mBatteryInfoReceiver=new BroadcastReceiver()
	 {
	  @Override
	  public void onReceive(Context context, Intent intent) {
	   // TODO Auto-generated method stub		 
	   String action=intent.getAction();
	   if(Intent.ACTION_BATTERY_CHANGED.equals(action))
	   {	 	  
         updateStatusBar(intent);    
	   }
	  } 
	 };
	 
   @Override
   public void onCreate() {
       mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
       mPendingIntent=PendingIntent.getActivity(MainService.this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
      // mPendingIntent=PendingIntent.getActivity(MainService.this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);jj
       mNotification=new Notification();  
       registerReceiver(mBatteryInfoReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
   }

   @Override
   public void onDestroy() {
   	unregisterReceiver(mBatteryInfoReceiver);
   	mNotificationManager.cancelAll();
   }

   @Override
   public IBinder onBind(Intent intent) {
   	return null;
   }
   
   void updateStatusBar(Intent intent)
   {
   	    int mLevel=intent.getIntExtra("level",0);
	 	int mScale=intent.getIntExtra("scale",100); 
	 	int cLevel=mLevel*100/mScale;
	 	
         mNotification.flags|=Notification.FLAG_NO_CLEAR;
   	     mNotification.icon=R.drawable.k+cLevel; 	    
	     mNotification.contentIntent=mPendingIntent;  
	     mNotification.setLatestEventInfo(MainService.this, getResources().getString(R.string.b_level)+" : "+String.valueOf(cLevel)+"%",getResources().getString(R.string.getInfo), mPendingIntent);
	     mNotificationManager.notify(0,mNotification);
   }
}
